/**
 * 根据注解apiRight的值，判断当前用户是否有权限执行该函数。只能作用springMVC函数
 */
package com.cnfangmao.right.impl;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cnfangmao.asserts.Asserter;
import com.cnfangmao.exception.PropertyException;
import com.cnfangmao.right.annotation.apiRights;
import com.cnfangmao.right.api.RightProcessor;
import com.cnfangmao.right.api.RightService;
import com.cnfangmao.right.api.Righter;
import com.cnfangmao.right.entity.Right;
import com.cnfangmao.right.exception.message.ExceptionMessagePkg;
import com.cnfangmao.threadscope.ThreadScopeVariableUtil;


@SuppressWarnings("deprecation")
@Configuration
public class ApiRightWEBMVCIntercepter  extends WebMvcConfigurerAdapter {
	private Map<String,RightProcessor> mapProcessors=new HashMap<String,RightProcessor>();
	
	@Autowired
	private RightService rightService;
	
	private class InternalInterceptor  extends HandlerInterceptorAdapter 
	{

		@Override
		public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
				throws Exception {
		}

		@Override
		public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
				throws Exception {
			
		}

		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
			
			Righter user=null;
			
	        if (!(arg2 instanceof HandlerMethod)) 
	        {
	            return super.preHandle(request, response, arg2);
	        }
			
	        if(ThreadScopeVariableUtil.getUser()!=null )
	        {//当前用户已登录
	        	Asserter.isAssignable(Righter.class, ThreadScopeVariableUtil.getUser().getClass());
	        	user=(Righter)ThreadScopeVariableUtil.getUser();
	        }

			HandlerMethod method=(HandlerMethod)arg2;
			apiRights rights=method.getMethodAnnotation(apiRights.class);
			if(rights!=null)
			{//目标函数配置了apiRights注解
				String[] aryRights=rights.value();
				for(String strRight:aryRights)
				{
					Right right=rightService.getRight(strRight);
					
					if(StringUtils.isNotBlank(right.getProcessor()))
					{//假如该权限有处理接口
						RightProcessor processor=mapProcessors.get(right.getProcessor());
						if(processor==null)
						{
							try
							{
								processor=(RightProcessor) Class.forName(right.getProcessor()).newInstance();
								mapProcessors.put(right.getProcessor(), processor);
							}
							catch(ClassNotFoundException e)
							{
								throw new PropertyException("exception.rightprocessor.notfound",ExceptionMessagePkg.class.getPackage().getName(),right.getProcessor());
							}
						}
						if(processor!=null)
						{
							processor.Process(user);
						}
					}
					else if(!user.checkRight(strRight))
					{//没有相应权限，抛出例外
						throw new PropertyException("exception.no.right",ExceptionMessagePkg.class.getPackage().getName(),right.getCName());	
					}
				}
			}
			
			return true;
		}
		
	}
	
	@Bean
	public InternalInterceptor getInternalInterceptor()
	{
		return new InternalInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getInternalInterceptor()).addPathPatterns("/**");
		super.addInterceptors(registry);
	}

}
